package com.game.othello;

public class OthelloBoard {
    public static final int EMPTY = 0;
    public static final int BLACK = 1;
    public static final int WHITE = 2;

    private final int size;
    private final int[][] board;

    public OthelloBoard(int size) {
        this.size = size;
        this.board = new int[size][size];
        initializeBoard();
    }

    private void initializeBoard() {
        // 初始化棋盘，放置初始的四个棋子
        int mid = size / 2;
        board[mid - 1][mid - 1] = WHITE;
        board[mid - 1][mid] = BLACK;
        board[mid][mid - 1] = BLACK;
        board[mid][mid] = WHITE;
    }

    public void placeStone(int x, int y, int stone) {
        board[y][x] = stone;
        flipStones(x, y, stone);
    }

    public int getStone(int x, int y) {
        return board[y][x];
    }

    public boolean isValidMove(int x, int y, int stone) {
        if (board[y][x] != EMPTY) {
            return false;
        }

        int opponent = (stone == BLACK) ? WHITE : BLACK;
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                if (dx == 0 && dy == 0) continue;
                if (canFlip(x, y, dx, dy, stone, opponent)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean canFlip(int x, int y, int dx, int dy, int stone, int opponent) {
        int count = 0;
        int nx = x + dx;
        int ny = y + dy;
        while (nx >= 0 && nx < size && ny >= 0 && ny < size && board[ny][nx] == opponent) {
            nx += dx;
            ny += dy;
            count++;
        }
        return (count > 0 && nx >= 0 && nx < size && ny >= 0 && ny < size && board[ny][nx] == stone);
    }

    private void flipStones(int x, int y, int stone) {
        int opponent = (stone == BLACK) ? WHITE : BLACK;
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                if (dx == 0 && dy == 0) continue;
                if (canFlip(x, y, dx, dy, stone, opponent)) {
                    int nx = x + dx;
                    int ny = y + dy;
                    while (board[ny][nx] == opponent) {
                        board[ny][nx] = stone;
                        nx += dx;
                        ny += dy;
                    }
                }
            }
        }
    }
}